package com.vd.wmt.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.vd.wmt.interactive.SendMailOprIntf;
import com.vd.wmt.model.WageInfo;

public class MailSender {
	private Integer counter = 0;
	private Integer max = 0;
	private boolean running = true;
	private SendMailOprIntf oprIntr;
	private Properties props;

	public MailSender(SendMailOprIntf oprIntr) {
		this.oprIntr = oprIntr;
		this.max = oprIntr.getWageList().size();
	}

	public void start() {
		props = new Properties();
		props.put("mail.smtp.host", "");
		props.put("mail.smtp.connectiontimeout", "60000");
		props.put("mail.smtp.timeout", "60000");
		props.put("mail.smtp.socketFactory.port", );
		
		Thread[] trds = new Thread[15];
		for (int i = 0; i < 5; i++) {
			trds[i] = new Thread(new SendTask());
			trds[i].start();
		}
	/*	try {
			for (int i = 0; i < 15; i++) {
				trds[i].join();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		oprIntr.showTipMsg("邮件发送完成");*/
	}

	protected class SendTask implements Runnable {
		@Override
		public void run() {
			while (running) {
				
				Integer work_index;
				synchronized (counter) {
					if (counter < max) {
						work_index = counter;
						counter++;
					} else {
						running = false;
						break;
					}
				}
				if (work_index == null) {
					break;
				}
				System.err.println(work_index);
				oprIntr.updateSendSts(work_index, "Sending");
				WageInfo wi = oprIntr.getWageList().get(work_index);
				BeanToXmlParse parse = BeanToXmlParse.getInstance();
				parse.putArgs("wage", wi, null);
				parse.putArgs("month", oprIntr.getWageMonth(), null);
				try {
					
					String xml = parse.parse("tmpl/mail.vm");
					Session session = Session.getDefaultInstance(props, new Authenticator() {
						@Override
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(oprIntr.getUserName(),
									oprIntr.getPassword());
						}
					});
					Message msg = new MimeMessage(session);
					InternetAddress addressFrom = new InternetAddress(oprIntr
							.getUserName()
							+ "@mail.tobosoft.com.cn");
					msg.setFrom(addressFrom);
					msg.setRecipient(Message.RecipientType.TO,
							new InternetAddress(wi.getEmail()));

					msg.setSubject(oprIntr.getWageMonth() + "份工资条");
					msg.setContent(xml, "text/html;charset=gb2312");
					msg.setSentDate(new Date());
					Transport.send(msg);
					oprIntr.updateSendSts(work_index, "SUCC");
					//Thread.sleep(5*1000);
				} catch (Exception e) {
					oprIntr.updateSendSts(work_index, "FALID");
					e.printStackTrace();
				}
				
			}
		}

	}

}